// --------------------------------
// YM.ui
// --------------------------------
(function($) {
	if (!$ || !window.YM) return;
	// ----------------------------
	YM.namespace('YM.utilStyles');
	$.extend(YM.utilStyles, {
		'util-floattop': 'z-index:1000;display:none;position:fixed;top:0;left:0;right:0;',
		'util-floattop_ie6': 'z-index:1000;display:none;position:absolute;top:expression(eval(document.documentElement.scrollTop));left:0;right:0;',
		'float-errortip': 'padding:5px;border:solid 1px #f00;background-color:#ffd;color:#f00;position:absolute;z-index:1000'
	});
	// ----------------------------
	YM.namespace('YM.base');
	YM.namespace('YM.ui');
	// ----------------------------
	YM.ui.bindElementParam = function(elm, params) {
		elm.each(function() {
			this._param =  this._param || {};
			$.extend(this._param, params || $(this).attrJSON());
		});
	};
	// ----------------------------
	// 显示/隐藏被遮盖对象（主要用于IE6中的object/iframe/select在有遮盖层时的显示hack)
	YM.ui.ShowOverElements = function(elm, element) {
		$(element).each(function() {
			if (this._hide) {
				this.style.visibility = 'visible';
				this._hide = false;
			}
		});
	};
	YM.ui.HideOverElements = function(elm, element) {
		var ox = elm.offset().left;
		var oy = elm.offset().top;
		var ow = elm.width();
		var oh = elm.height();
		$(element).each(function() {
			var pos = $(this).offset();
			if (!(ox>(pos.left+$(this).width()) || pos.left>(ox+ow) || pos.top>(oy+oh) || oy>(pos.top+$(this).height()))) {
				this.style.visibility = 'hidden';
				this._hide = true;
			}
		});
	};
	// ----------------------------
	// 定时关闭(隐藏)div图层
	// 触发样式：e-hidebytimer
	YM.ui.HideByTimer = function(elm, params) {
		elm.each(function() {
			var element = $(this);
			var param = params || element.attrJSON();
			setTimeout(function() {
				if (param.animate == 'slide') {
					element.slideUp();
				} else if (param.animate == 'fade') {
					element.fadeOut();
				} else {
					element.hide();
				}
			}, (param.timer||3)*1000);
		});
	};
	// ----------------------------
	// 触发样式：e-elementhover
	YM.ui.ElementHover = function(elm, params) {
		if (elm.data('ElementHover-binded')) return;
		YM.ui.bindElementParam(elm, params);
		elm.hover(function() {
			$(this).addClass(this._param.hoverClass);
		}, function() {
			$(this).removeClass(this._param.hoverClass); 
		});
	};
	// ----------------------------
	// 触发样式：e-childhoverview
	YM.ui.ChildHoverView = function(elm, params) {
		if (elm.data('ChildHoverView-binded')) return;
		YM.ui.bindElementParam(elm, params);
		elm.hover(function() {
			$(this).find(this._param.hoverChild).show();
		}, function() {
			$(this).find(this._param.hoverChild).hide();
		});
	};
	// ----------------------------
	// 输入限制： 只能输入整数或小数
	// 使用一： $('input').bindYMUI('InputLimit', { limitType:'integer' });
	// 触发样式：e-inputlimit
	YM.ui.InputLimit = function(elm, params) {
		if (elm.data('InputLimit-binded')) return;
		YM.ui.bindElementParam(elm, params);
		elm.css('ime-mode', 'disabled');
		elm.bind('keypress', function(e) {
			try {
				if (e.shiftKey) return false;
                var code = e.which || e.keyCode || 0;
                switch (this._param.limitType) {
                    case 'float': //浮点数/小数
                        return code == 8 || (e.which == 0 && e.keyCode == 37) || (e.which == 0 && e.keyCode == 39) || (code >= 48 && code <= 57) || code == 46;
                    case 'integer': //整数
                        return code == 8 || (e.which == 0 && e.keyCode == 37) || (e.which == 0 && e.keyCode == 39) || (code >= 48 && code <= 57) || (e.which == 0 && e.keyCode == 46);
                }
                // 8:backspace / 37:left / 39:right / 46:del (FF: del为which=0,keyCode=46)
			} catch(err) {}
		});
		elm.bind('paste',function(){ return !clipboardData.getData('text').match(/\D/); });
		elm.bind('dragenter', function(){ return false; });
	};
	// 最少输入字数限制提示处理 params: { minlen, tips, pos, css, timer }
	// 触发样式： e-inputminlen
	YM.ui.InputMinLength = function(elm, params) {
		if (elm.data('InputMinLength-binded')) return;
		YM.ui.bindElementParam(elm, params);
		elm.bind('blur', function() {
			if (!this._param.minlen) return;
			var minlen = parseInt(this._param.minlen);
			if (this.value.trim().getByteLength()<minlen) {
				$(this).bindYMUI('FloatErrorTipText', this._param);
			}
		});
	};
	// 最多输入字数限制提示处理 params: { maxlen, tips, pos, css, timer }
	// 触发样式： e-inputmaxlen
	YM.ui.InputMaxLength = function(elm, params) {
		if (elm.data('InputMaxLength-binded')) return;
		YM.ui.bindElementParam(elm, params);
		elm.bind('keyup', function() {
			if (!this._param.maxlen) return;
			var maxlen = parseInt(this._param.maxlen);
			if (this.value.trim().getByteLength()>maxlen) {
				this.value = this.value.trim().subByte(maxlen, '');
				$(this).bindYMUI('FloatErrorTipText', this._param);
			} else if (this.value.trim().getByteLength()<=maxlen-2) {
				if ($(this).data('floaterrortip')) {
					$(this).data('floaterrortip').remove();
					$(this).data('floaterrortip', '')
				}
			}
		});
	};
	// 浮动Tips文字显示处理（会自动隐藏） params: { tips, pos, css, timer }
	YM.ui.FloatErrorTipText = function(elm, params) {
		if (!params || !params.tips) return;
		if (elm.data('floaterrortip')) return;
		var tipElm = $('<div style="'+ YM.utilStyles['float-errortip']+'">'+params.tips+'</div>');
		$('body').append(tipElm);
		if (params.pos && params.pos=='right') {
			tipElm.css({
				'width': '200px',
				'left': (elm.offset().left+elm.outerWidth()+5) +'px',
				'top': (elm.offset().top) +'px'
			});
		} else {
			tipElm.css({
				'width': (elm.outerWidth()-12)+'px',
				'left': (elm.offset().left) +'px',
				'top': (elm.offset().top+elm.outerHeight()+1) +'px'
			});			
		}
		if (params.css) tipElm.css(params.css);
		elm.data('floaterrortip', tipElm);
		setTimeout(function() {
			if (elm.data('floaterrortip')) {
				elm.data('floaterrortip').slideUp(function() {
					if (elm.data('floaterrortip')) {
						elm.data('floaterrortip').remove();
						elm.data('floaterrortip', '');
					}
				});
			};
		}, (params.timer||1)*1000);
	};
	// ----------------------------
	// 显示输入框默认文本
	// 使用一： $('input').bindYMUI('InputHint', { hint:'默认文本', required:true, hintKeep:false, hintClass:'', hintColor:'' });
	// 触发样式：e-inputhint
	YM.ui.InputHint = function(elm, params) {
		if (elm.data('InputHint-binded')) return;
		YM.ui.bindElementParam(elm, params);
		elm.each(function() {
			var domElm = this;
			if (!this.form) return;
			$(this.form).submit(function(e) {
				if (domElm._param.hintKeep && domElm._param.hintKeep!='false') return true;
				if ($.trim(domElm.value)=='' || $.trim(domElm.value)==domElm._param.hint) {
					if (domElm._param.required) {
						domElm.focus();
						if(e.preventDefault) e.preventDefault();
						return false;
					} else {
						domElm.value = '';
						return true;
					}
				}
			});
		});
		elm.bind('focus', function() {
			if (this._param.hintColor) $(this).css('color', '');
			if (this._param.hintClass) $(this).removeClass(this._param.hintClass);
			if ($.trim(this.value)==this._param.hint) $(this).val('');
		});
		elm.bind('blur', function() {
			if ($.trim(this.value)=='' || $.trim(this.value)==this._param.hint) {
				if (this._param.hintColor) $(this).css('color', this._param.hintColor);
				if (this._param.hintClass) $(this).addClass(this._param.hintClass);
				this.value = this._param.hint;
			}
		});
		elm.blur();
	};
	YM.ui.InputBGHint = function(elm, hintClass) {
		if (elm.data('InputBGHint-binded')) return;
		elm.each(function() {
			if (this.value=='') $(this).addClass(hintClass);			
		});
		elm.focus(function() {
			$(this).removeClass(hintClass);
		});
		elm.blur(function() {
			if (this.value=='') $(this).addClass(hintClass);
		});
	};
	// placeholder处理，用于不支持placeholder属性时的JS替代解决。
	YM.ui.InputPlaceHolder = function (elm, param) {
		if ('placeholder' in document.createElement('input')) return;
		if (elm.data('InputPlaceHolder-binded')) return;
		var param = param || {};
		elm.each(function() {
			var text = $(this).attr("placeholder");
			var cssdata = { 'position':'absolute', 'padding-left':'5px', 'line-height':($(this).outerHeight()||20)+'px', 'width':(($(this).width()>0)?($(this).width()+'px'):'auto'), 'color':param.color||'#999' };
			if ($(this).val()!='') cssdata.display = 'none';
			var mask = $('<div>').html(text).css(cssdata);
			$(this).after(mask);
			// 点击是隐藏
			mask.click(function() {
				$(this).prev().focus();
				$(this).hide();
			});
			mask.bind('resetPosition', function() {
				var pos = $(this).prev().position();
				$(this).css({'top':pos.top, 'left':pos.left});
			});
			mask.trigger('resetPosition');
			// 用于非focus时，值被改动后的处理
			this.onpropertychange = function() {				
				if (this.value!='' && !this.isFocus) {
					$(this).next().hide();
				}
			};
		});
		elm.focus(function() {
			this.isFocus = true;
			$(this).next().hide();
		});
		elm.blur(function() {
			this.isFocus = false;
			if (this.value=='') $(this).next().show().trigger('resetPosition');
		});
	};	
	// 日历选择
	YM.ui.DatePicker = function(elm) {
		if (elm.data('DatePicker-binded')) return;
		YM.load('lhgcalendar', function() {
			elm.each(function() {
				var input = $(this);
				var param = {};
				param.format = input.attr('data-format') || 'yyyy-MM-dd';
				if (input.attr('data-minDate')) param.minDate = input.attr('data-minDate');
				if (input.attr('data-maxDate')) param.maxDate = input.attr('data-maxDate');
				input.calendar(param);
			});
		});
	};
	// 全选
	YM.ui.CheckAll = function(elm) {
		elm.click(function() {
			var _this = this;
			var checklist = $(this).attr('data-checklist') || '';
			if (checklist == '') return;
			$(checklist).each(function() {
				this.checked = _this.checked;
				$(this).bindYMUI('CheckDataRow');
			});
		});
	};
    // 选中或取消选中当前行
    YM.ui.CheckDataRow = function(elm) {
        if (!elm.hasClass('e-checkdatarow')) return;
        if (elm.attr('checked')) {
            elm.closest('tr').addClass('selected');
        } else {
            elm.closest('tr').removeClass('selected');
        }
    };
	YM.ui.AddDataRowCheck = function(elm) {
		elm.click(function() {
			$(this).bindYMUI('CheckDataRow');
		});
	};
	YM.ui.PopDialogWin = function(elm, param) {
		var param = param || {};
		elm.click(function() {
			var title = $(this).attr('title') || $(this).text();
			var url = $(this).attr('data-url') || $(this).attr('href');
			var width = $(this).attr('data-win-width') || param.width;
			var height = $(this).attr('data-win-height') || param.height;
			YM.page.dialog.pop({title:title, url:url, width:parseInt(width,10), height:parseInt(height,10) });
			return false;
		});
	};
	// ----------------------------
	// Delayload，内容滚动延迟加载。
	// 使用： $(document).bindYMUI('DelayLoad', { eventClass:'e-delayload', callback:function() {} });
	YM.ui.DelayLoad = function(elm, params) {
		var params = params || {};
		var	eventClass = params.eventClass || 'e-delayload';
		var delayLoad = function() {
			var elms = $('.'+eventClass);
			if (elms.size()==0) {
				$(window).unbind('scroll', delayLoad);
				$(window).unbind('resize', delayLoad);
			} else {
				var preloadHeight = params.preloadHeight || 0;
				elms.each(function() {
					var element = $(this);
					if (element.offset().top > $(window).height()+$(document).scrollTop()+preloadHeight) return;
					params.callback(element);
					element.removeClass(eventClass);
				});
			}
		};
		$(window).bind('scroll', delayLoad);
		$(window).bind('resize', delayLoad);
		delayLoad();
	};
	// Ajax内容滚动延迟加载处理
	// 使用： $(document).bindYMUI('AjaxDelayLoad');
	YM.ui.AjaxDelayLoad = function(elm, params) {
		var params = params || {};
		elm.bindYMUI('DelayLoad', {
			preloadHeight: params.preloadHeight || 100,
			eventClass: params.eventClass || 'e-ajaxload',
			callback: function(element) {
				element.load(element.attr('data-url'), function() {
					element.bindYMUI('LoadMVC');
					element.bindYMUI('LoadElementEvent');
					if (params.callback) params.callback(element);
				});				
			}
		});
	};
	// 图片内容滚动延迟加载处理
	// 使用： $(document).bindYMUI('ImageDelayLoad');
	YM.ui.ImageDelayLoad = function(elm, params) {
		var params = params || { preloadHeight:100, eventClass:'e-imageload' };
		var	eventClass = params.eventClass || 'e-imageload';
		var imageDelayLoad = function() {
			var elms = $('.'+eventClass);
			if (elms.size()==0) {
				$(window).unbind('scroll', imageDelayLoad);
				$(window).unbind('resize', imageDelayLoad);
			} else {
				elms.bindYMUI('DelayLoadImage', params);
			}
		};
		$(window).bind('scroll', imageDelayLoad);
		$(window).bind('resize', imageDelayLoad);
		imageDelayLoad();
	};
	YM.ui.AddImageDelayLoad = function(elm) {
		if ($('.e-imageload').size()==0) {
			elm.addClass('e-imageload');
			elm.bindYMUI('ImageDelayLoad');
		} else {
			if (elm.parents('.e-imageload').size()==0 && !elm.hasClass('e-imageload')) {
				elm.addClass('e-imageload');
			}
			elm.bindYMUI('DelayLoadImage', {preloadHeight:100});
		}
	};
	// 图片延迟加载处理
	YM.ui.DelayLoadImage = function(elm, params) {
		var params = params || {};
		var	eventClass = params.eventClass || 'e-imageload';
		var preloadHeight = params.preloadHeight || 0;
		elm.each(function() {
			var element = $(this);
			if (!element.hasClass(eventClass)) return;
			if (element.offset().top > $(window).height()+$(document).scrollTop()+preloadHeight) return;
			element.find('img[realSrc]').each(function() {
				if ($(this).offset().top < $(window).height()+$(document).scrollTop()+preloadHeight) {
					$(this).bindYMUI('LoadRealImage', {srcAttr:'realSrc'});
				}
			});
			element.find('img[original]').each(function() {
				if ($(this).offset().top < $(window).height()+$(document).scrollTop()+preloadHeight) {
					$(this).bindYMUI('LoadRealImage', {srcAttr:'original'});
				}
			});
			if (element.find('img[realSrc], img[original]').size()==0) {
				element.removeClass(eventClass);
			}
		});
	};
	// 加载容器中的图片内容, eventClass最好固定用e-childload
	YM.ui.LoadChildImage = function(elm, params) {
		var params = params || {};
		var eventClass = params.eventClass || 'e-childload';
		elm.each(function() {
			var element = $(this);
			if (!element.hasClass(eventClass)) return;
			element.removeClass(eventClass);
			element.find('img[realSrc]').each(function() {
				$(this).bindYMUI('LoadRealImage', {srcAttr:'realSrc'});
			});
			element.find('img[original]').each(function() {
				$(this).bindYMUI('LoadRealImage', {srcAttr:'original'});
			});
		});
	};
	// 图片加载
	YM.ui.LoadRealImage = function(elm, params) {
		elm.each(function() {
			var element = $(this);
			var param = params || element.attrJSON();
			var realSrc = element.attr(param.srcAttr || 'realSrc') || '';
			var errorSrc = param.errorUrl || 'http://img02.yesmywine.com/newWeb/images/global/noimage_110x180.jpg';
			if (realSrc) {
				if (param.autoScale || param.autoMargin || param.autoPadding) {
					var oW = element.attr('width') || element.width() || param.width || 80;
					var oH = element.attr('height') || element.height() || param.height || 80;
					var imgObj = new YM.base.ImageLoader({
						src: realSrc,
						onLoad: function() {
							element.removeAttr(param.srcAttr || 'realSrc');
							element.attr('src', this.element.src);
							var w = this.element.width;
							var h = this.element.height;
							if (w && h) {
								var _w = 0;
								var _h = 0;
								if (w/h>=oW/oH) {
									_w = oW; _h = (h*oW)/w;
									if (w < oW && param.autoScale) {
										_w = w; _h = h;
									}
								} else { 
									_w = (w*oH)/h; _h = oH;
									if (h < oH && param.autoScale) {
										_w = w; _h = h;
									}
								}
								var m_w = parseInt((oW - _w) / 2);
								var m_h = parseInt((oH - _h) / 2);
								element.css({width:_w+'px', height:_h+'px'});
								if (param.autoMargin)  element.css({marginTop:m_h, marginLeft:m_w});
								if (param.autoPadding) element.css('padding', m_h+'px '+m_w+'px');
							}
						},
						onError: function() {
							element.attr('src', errorSrc);
						}
					});
				} else {
					if (element.hasClass('e-pngfix') && $.browser.isIE6) {
						element.bindYMUI('FixIE6PNG', { srcAttr:(param.srcAttr||'realSrc') });
						element.removeAttr(param.srcAttr || 'realSrc');
					} else {
						element.attr('src', realSrc);
						element.removeAttr(param.srcAttr || 'realSrc');
					}
					YM.debug('load image', realSrc);
				}
			}
		});
	};
	// ImageLoader: 图像加载器
	YM.base.ImageLoader = function(options) {
		this.options = $.extend({src:'', min:0.5, max:30, timer:0.1}, options || {});
		this.minTimeout = this.options.min * 1000;
		this.maxTimeout = this.options.max * 1000;
		this.intervalTimer = this.options.timer * 1000;
		this.theTimeout = 0;
		this.loadStatus = 0;
		this.loaderId = (new Date()).getTime();
		this.onLoad = this.options.onLoad || null;
		this.onError = this.options.onError || null;
		var m_this = this;
		this.init = function() {
			this.element = new Image();
			this.element.onload = function() {
				m_this.complete(1);
				YM.debug('image onload', m_this.loaderId +': '+ this.width +','+ this.height);
			};
			this.element.onerror = function() {
				m_this.complete(-1);
				YM.debug('image onerror', m_this.loaderId);
			};
			this.element.src = this.options.src;
			this.startMonitor();
			YM.debug('image init', m_this.loaderId);
		};
		this.complete = function(status) {
			if (this.loadStatus != 0) return;
			this.loadStatus = status;
			if (status == 1) {
				if (this.onLoad) this.onLoad();
			} else {
				if (this.onError) this.onError();				
			}
		};
		this.startMonitor = function() {
			var m_this = this;
			setTimeout(function() {
				m_this.checkMonitor();
			}, this.minTimeout);
		};
		this.checkMonitor = function() {
			if (this.loadStatus != 0) return;
			this.theTimeout = this.minTimeout;
			this._monitor = setInterval(function() {
				m_this.theTimeout += 50;
				if (m_this.loadStatus != 0) {
					clearInterval(m_this._monitor);
				} else if (m_this.element.complete) {
					clearInterval(m_this._monitor);
					m_this.complete(1);
					YM.debug('image complete', m_this.loaderId +': '+ m_this.element.width +','+ m_this.element.height);
				} else if (m_this.theTimeout >= m_this.maxTimeout) {
					clearInterval(m_this._monitor);
					m_this.complete(-1);
					YM.debug('image timeout', m_this.loaderId);
				}
			}, m_this.intervalTimer);
		};
		this.init();
	};
	// 用于IE6下修复png透明问题
	YM.ui.FixIE6PNG = function(elm, params) {
		if (!$.browser.isIE6) return;
		var params = params || {};
		elm.each(function() {
			var element = $(this);
			var blankSrc = 'http://img02.yesmywine.com/newWeb/images/global/1px.gif',
				realSrc = element.attr(params.srcAttr||'src') || '',
				width = (params.width || element.attr('width') || element.width()),
				height = (params.height || element.attr('height') || element.height());
			element.attr('src', blankSrc);
			element.attr('style', "background:transparent;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+realSrc+"',sizingMethod='scale');");
			element.css({width: width+'px', height: height+'px'});
		});
	};
	// ----------------------------
	// 简单Tab切换处理
	// 使用一： $('#tab li').bindYMUI('SwitchTabs', { action:'click', child:'#content li' });
	YM.ui.SwitchTabs = function(elm, params) {
		if (elm.data('SwitchTabs-binded')) return;
		var params = params || {};
		var tabAction = params.action || 'click';
		var tabClass = params.tabClass || 'on';
		var childClass = params.childClass || 'on';
		var childItems = params.child;
		var callback = params.callback;
		elm.bind(tabAction, function() {
			var element = $(this);
			if (element.hasClass(tabClass)) return;
			element.siblings('.'+tabClass).removeClass(tabClass);
			element.addClass(tabClass);
			var idx = element.attr('data-index') || elm.index(this);
			$(childItems+'.'+childClass).removeClass(childClass);
			$(childItems+':eq('+ idx +')').addClass(childClass);
			if (callback) callback($(childItems+':eq('+ idx +')'));
			return false;
		});
	};
	// ----------------------------
	// 滚动加载处理
	// param: { url, page, preheight, lastClass, afterLoad }
	YM.ui.LoadDataByScroll = function(elm, param) {
		if (elm.data('LoadDataByScroll-binded')) return;
		var param = param || {};
		param.lastClass = param.lastClass || 'lastitem';
		if (param.url) elm.attr('data-url', param.url);
		if (param.page) elm.attr('data-page', param.page);
		if (param.preheight) elm.attr('data-preheight', param.preheight);
		elm.data('scrollingStatus', (elm.children('.'+param.lastClass).size()==0));
		elm.bind('ContentLoad', function() {
			var that = $(this);
			that.data('scrollingStatus', false);
			var page = parseInt(that.attr('data-page') || 1);
			var url = that.attr('data-url').format(page);
			var childSize = that.children().size();
			$.get(url, function(d) {
				if (page==1) that.html('');
				that.append(d);
				var newItems = that.children(':gt('+ (childSize-1) +')');
				if (param.afterLoad) param.afterLoad(newItems);
				if (that.children('.'+param.lastClass).size()==0) {
					that.attr('data-page', page+1);
					that.data('scrollingStatus', true);
				} else {
					that.data('scrollingStatus', false);
				}
			});
		});
		elm.bind('ContentScroll', function() {
			var that = $(this);
			if (!that.data('scrollingStatus') || that.children().size()==0) return;
			var preheight = that.attr('data-preheight') || that.children(':first').outerHeight();
			if ($(window).height()+$(document).scrollTop() > that.offset().top+that.outerHeight()-preheight) {
				that.trigger('ContentLoad');
			}
		});
		$(window).scroll(function() {
			elm.trigger('ContentScroll');
		});
		$(document).ready(function() {
			elm.trigger('ContentScroll');
		});
	};
	// ----------------------------
	// 滚动加载处理, param: { secAttr, callback }
	YM.ui.CountDown = function(elm, param) {
		if (elm.data('CountDown-binded')) return;
		var setCountDownStr = function(element, seconds) {
			if (seconds<0) return;
			var s = seconds%60, m = Math.floor((seconds%3600)/60), h = Math.floor(seconds/3600), d = 0;
			if (element.find('.tcd-d').size()>0) {
				h = Math.floor((seconds%86400)/3600);
				d = Math.floor(seconds/86400);
			}
			element.find('.tcd-d').html(d);
			element.find('.tcd-h').html(h.padLeft(element.data('hlen'),'0'));
			element.find('.tcd-m').html(m.padLeft(element.data('mlen'),'0'));
			element.find('.tcd-s').html(s.padLeft(element.data('slen'),'0'));
		};
		var params = param || elm.attrJSON();
		elm.each(function() {
			var element = $(this);
			element.data('hlen', element.find('.tcd-h').text().length||2);
			element.data('mlen', element.find('.tcd-m').text().length||2);
			element.data('slen', element.find('.tcd-s').text().length||2);
			//
			var millseconds, seconds;
			if (element.attr('data-end')) {
				millseconds =  element.attr('data-end').parseDate().getTime() - new Date().getTime();
				seconds = Math.round(millseconds/1000);
			} else {
				millseconds = parseInt(element.attr(params.secAttr||'millseconds')||0);
				seconds = Math.round(millseconds/1000);
				if (YM.timestat && YM.timestat.loadTime) {
					seconds = Math.round((millseconds - new Date().getTime() + YM.timestat.loadTime)/1000);
				}
			}
			var timer = setInterval(function() {
				seconds --;
				setCountDownStr(element, seconds);
				if (seconds<=0) {
					clearInterval(timer);
					if (params.callback) params.callback(element);
				}
			}, 1000);
			setCountDownStr(element, seconds);
		});
	};
	// ----------------------------
	// 页面顶部浮动栏处理 params: { child, top }
	YM.ui.floatTopNav = function(elm, params) {
		if (elm.data('floatTopNav-binded')) return;
		var utilId = 'util-floattop'; 
		if ($('#'+utilId).size()==0) {
			var style = ($.browser.isIE6) ? YM.utilStyles[utilId+'_ie6']: YM.utilStyles[utilId];
			$('body').append('<div id="'+ utilId +'" style="'+ style +'"></div>');
		}
		var fixContainer = $('#'+utilId), floatTop = 0, floatStatus = false, container = elm.parent();
		var params = params || elm.attrJSON();
		elm.bind('pageScroll', function() {
			var element = $(this);
			var scrollTop = $(document).scrollTop() + (params.top||0);
			if (floatStatus) {
				if (scrollTop < floatTop) {
					floatStatus = false;
					fixContainer.hide();
					container.append(element);
					if (params.top) element.css('margin-top', 0);
					if (params.child) element.find(params.child).fadeOut();
				}
			} else {
				if (scrollTop > element.offset().top) {
					floatTop = element.offset().top;
					floatStatus = true;
					fixContainer.append(element);
					fixContainer.show();
					if (params.top) element.css('margin-top', params.top+'px');
					if (params.child) element.find(params.child).fadeIn();
				}
			}
		});
		$(window).scroll(function() {
			elm.trigger('pageScroll');
		});
		elm.trigger('pageScroll');
	};
	// ----------------------------
	// 快速导航浮动栏处理（紧贴在内容右侧的） params: { mainWidth, baseTop, floatTop }
	YM.ui.FloatTool = function(elm, params) {
		if (elm.data('FloatTool-binded')) return;
		var params = params || elm.attrJSON();
		params.mainWidth = params.mainWidth || 970;
		params.baseTop   = params.baseTop || 600;
		params.floatTop  = params.floatTop || 20;
		params.minWidth  = params.mainWidth + (elm.outerWidth()*2);
		elm.bind('pageResize', function() {
			var element = $(this);
			if (params.minWidth && $(window).width()<params.minWidth) {
				element.css('left', '-1000px');
			} else {
				element.css('left', (($(window).width()-params.mainWidth)/2+params.mainWidth)+'px');
			}
		});
		$(window).resize(function() {
			elm.trigger('pageResize');
		});
		elm.bind('pageScroll', function() {
			if (params.minWidth && $(window).width()<params.minWidth) return;
			if ($(document).scrollTop()<=params.baseTop-params.floatTop) {
				elm.css({position:'absolute', top:params.baseTop+'px'});
			} else {
				if (!$.browser.isIE6) {
					elm.css({position:'fixed', top:params.floatTop+'px'});
				} else {
					elm.css('top', ($(document).scrollTop()+params.floatTop)+'px');
				}
			}
		});
		$(window).scroll(function() {
			elm.trigger('pageScroll');
		});
		elm.trigger('pageResize');
		elm.trigger('pageScroll');
	};
	// ----------------------------
	// 右侧底部浮动栏处理 params: { minWidth, mainWidth, floatBottom }
	YM.ui.FloatBottomTool = function(elm, params) {
		if (elm.data('FloatBottomTool-binded')) return;
		var params = params || elm.attrJSON();
		if (params.minWidth || params.mainWidth) {
			elm.bind('pageResize', function() {
				var element = $(this);
				if (params.mainWidth) {
					element.css('right', 'auto');
					element.css('left', (($(window).width()-params.mainWidth)/2+params.mainWidth)+'px');					
				}
				if (!params.minWidth || $(document).scrollTop()==0) return;
				if ($(window).width()<params.minWidth) {
					if (element.attr('status')=='show') element.attr('status','hide').fadeOut();
				} else {
					if (element.attr('status')!='show') element.attr('status','show').fadeIn();
				}
			});
			$(window).resize(function() {
				elm.trigger('pageResize');
			});
			elm.trigger('pageResize');
		}
		elm.bind('pageScroll', function() {
			var element = $(this);
			if (params.minWidth && $(window).width()<params.minWidth) return;
			if ($(document).scrollTop()==0) {
				if (element.attr('status')=='show') element.attr('status','hide').fadeOut();
			} else {
				if (element.attr('status')!='show') element.attr('status','show').fadeIn();
				if (params.floatBottom) {
					var _bottom = $(document).height() - $(document).scrollTop() - $(window).height();
					if (_bottom<params.floatBottom) {
						element.css('margin-bottom', params.floatBottom-_bottom+'px');
					} else {
						element.css('margin-bottom', 0);
					}
				}				
			}
		});
		$(window).scroll(function() {
			elm.trigger('pageScroll');
		});
		elm.trigger('pageScroll');
	};
	// ----------------------------
	YM.ui.SlideByPage = function(elm, options) {
		if (elm.data('SlideByPage-binded')) return;
		var settings = $.extend({
			items:		'ul.slide-items',
			btnPrev:	'.btn-prev',
			btnNext:	'.btn-next',
			pageElm:	'.txt-page',
			pageTmpl:	'{page}/{pages}',
			pagesize:	1,
			autoslide:  false,
			direction:  'left',	//left,top
			duration:   0.3,	//unit:seconds
			delay:      3		//unit:seconds
		}, options||{});
		var ulElm = elm.find(settings.items), lisElm = ulElm.children(), btnPrev = elm.find(settings.btnPrev), btnNext = elm.find(settings.btnNext), pageElm = elm.find(settings.pageElm);
		var li_num = lisElm.size(), li_height = 0, li_width = 0, page = 1, pages = 0, pagesize = settings.pagesize, margin = 0, autodir = 'left';
		// 初始化
		var init = function() {
			if (!elm.size()) return false;
			// set pages
			pages = parseInt(li_num / settings.pagesize);
			lastpagesize = li_num % settings.pagesize;
			if (li_num%settings.pagesize!=0) pages++;
			// set ul's width/height
			li_width  = settings.unitwidth || lisElm.first().outerWidth();
			li_height = settings.unitheight || lisElm.first().outerHeight();
			if (settings.direction == 'left') {
				maxmargin = (li_num - pagesize) * li_width;
				ulElm.css('width', (li_num+1)*li_width + 'px');
			} else {
				maxmargin = (li_num - pagesize) * li_height;
				ulElm.css('height', (li_num+1)*li_height + 'px');
			}
			//
			btnPrev.addClass('disabled');
			if (li_num <= pagesize) btnNext.addClass('disabled');
			btnPrev.click(function() {
				if ($(this).hasClass('disabled')) return;
				page --;
				margin = margin - pagesize;
				if (margin < 0) margin = 0;
				btnNext.removeClass('disabled');
				autodir = 'right';
				if (page<=1) {
					$(this).addClass('disabled');
					autodir = 'left';
				}
				startSlide();
			});
			btnNext.click(function() {
				if ($(this).hasClass('disabled')) return;
				page ++;
				margin = margin + pagesize;
				if (margin > (li_num-pagesize)) margin = li_num-pagesize;
				btnPrev.removeClass('disabled');
				autodir = 'left';
				if (page >= pages) {
					$(this).addClass('disabled');
					autodir = 'right';
				}
				startSlide();
			});
			showPage();
			if (settings.callback) settings.callback(ulElm.children(':lt('+ pagesize +')'));
			// start
			autoSlide();
			if (settings.autoslide) {
				// 鼠标经过事件
				elm.hover(function() {
					stopSlide();
				}, function() {
					autoSlide(); 
				});
			};
		};
		var showPage = function() {
			pageElm.html(settings.pageTmpl.substitute({page:page, pages:pages}));
		};
		// 开始轮播
		var startSlide = function() {
			stopSlide();
			if (settings.direction == 'left') {
				offset = margin * li_width * -1;
				param = {'margin-left': offset + 'px' };
			} else {
				offset = margin * li_height * -1;
				param = {'margin-top': offset + 'px' };
			}
			ulElm.stop().animate(param, settings.duration*1000, 'linear', function() {
				showPage();
			});
			if (settings.callback) settings.callback(ulElm.children(':lt('+ (margin+pagesize) +')').filter(':gt('+(margin-1)+')'));
			//
			autoSlide();
		};
		// 停止轮播
		var stopSlide = function() {
			if (elm.data('timeid')) window.clearTimeout(elm.data('timeid'));
		};
		var autoSlide = function() {
			if (settings.autoslide) {
				elm.data('timeid', window.setTimeout(function() {
					if (autodir=='left') {
						btnNext.click();
					} else {
						btnPrev.click();
					}					
				}, settings.delay*1000));
			}			
		};
		init();
	}; 
	// 内容Slide展示效果
	YM.ui.SlideBox = function(elm, options) {
		if (elm.data('SlideBox-binded')) return;
		if (elm.size()==0) return;
		// 默认参数
		var settings = $.extend({
			items:      'ul.slide-items',
		//	title:      'slide-title',
			index:      'slide-index',
			action:     'mouseover',
			animate:	'slide',
			autoslide:  true,
			direction:  'left',	//left,top
			duration:   0.3,	//unit:seconds
			delay:      5		//unit:seconds
		}, options||{});
		// 计算相关数据
		var ulElm = elm.find(settings.items), lisElm = ulElm.children(), li_num = lisElm.size(), li_height = 0, li_width = 0;
		// 定义滚动顺序: ASC/DESC
		var order_by = 'ASC', index = 0;
		// 初始化
		var init = function() {
			if (li_num<=1) return false;
			var active = lisElm.eq(index);
			active.addClass('active');
			if (settings.animate=='fade') {
				active.siblings().hide();
			} else {
				// set ul's width/height
				li_width  = settings.unitwidth || lisElm.first().width();
				li_height = settings.unitheight || lisElm.first().height();
				if (settings.direction == 'left') {
					ulElm.css('width', li_num * li_width + 'px');
				} else {
					ulElm.css('height', li_num * li_height + 'px');
				}
			}
			// create title
			if (settings.title) {
				var titleElm = elm.find('.'+settings.title);
				if (titleElm.size()==0) {
					titleElm = $('<div class="'+ settings.title + '"></div>').appendTo(elm);
				}
				titleElm.html(function() {
					var active_a = active.find('a'), text = active_a.attr('title'), href = active_a.attr('href'), target = active_a.attr('target');
					return $('<a>').attr('href', href).attr('target', target).text(text);
				});
			}
			// create nums
			if (settings.index) {
				var indexElm = elm.find('.'+settings.index);
				if (indexElm.size()==0) {
					indexElm = $('<div class="'+ settings.index + '"></div>').appendTo(elm);
				}
				if (indexElm.text()=='') {
					indexElm.html('');
					lisElm.each(function(i, n) {
						var css = (i == index)?'active':'';
						$('<span>').text(i+1).addClass(css).appendTo(indexElm);
					});
				}
				indexElm.children().bind(settings.action, function() {
					if ($(this).hasClass('active')) return;
					startSlide($(this).index());
				});
			}
			// start
			autoSlide();
			if (settings.autoslide) {
				// 鼠标经过事件
				elm.hover(function() {
					stopSlide();
				}, function() {
					autoSlide(); 
				});
			};
		};
		// 开始轮播
		var startSlide = function(idx) {
			stopSlide();
			if (typeof(idx)!='undefined') {
				order_by = (idx>index)?'ASC':'DESC';
				index = idx;
			} else if(settings.animate=='fade') {
				index ++;
				if (index >= li_num) index = 0;
			} else {
				if (order_by=='ASC') {
					if (index < li_num - 1) {
						index ++;
					} else {
						order_by = 'DESC';
						index = li_num - 2;
					}
				} else if(order_by=='DESC') {
					if (index > 0) {
						index --;
					} else {
						order_by = 'ASC';
						index = 1;
					}
				}
			}
			//
			var active = lisElm.eq(index);
			if (settings.index) {
				elm.find('.'+settings.index).children(':eq('+index+')').addClass('active').siblings().removeClass('active');
			}
			if (settings.title) {
				var active_a = active.find('a');
				elm.find('.'+settings.title).find('a').attr('href', active_a.attr('href')).text(active_a.attr('title'));
			}
			//
			if (settings.animate=='fade') {
				active.addClass('active').siblings('.active').hide().removeClass('active');
				active.fadeIn(settings.duration*1000, 'linear');
			} else {
				active.addClass('active').siblings().removeClass('active');
				if (settings.direction == 'left') {
					offset = index * li_width * -1;
					param = {'margin-left': offset + 'px' };
				} else {
					offset = index * li_height * -1;
					param = {'margin-top': offset + 'px' };
				}
				ulElm.stop().animate(param, settings.duration*1000, 'linear');
			}
			if (settings.callback) {
				settings.callback(active);
			}
			autoSlide();
		};
		// 停止轮播
		var stopSlide = function() {
			if (elm.data('timeid')) window.clearTimeout(elm.data('timeid'));
		};
		var autoSlide = function() {
			if (settings.autoslide) {
				elm.data('timeid', window.setTimeout(startSlide, settings.delay*1000));
			}			
		};
		init();
	};
	// 文字跑马灯效果（往左）
	YM.ui.TextLeftMarqueen = function(elm, options) {
		var settings = $.extend({
			items: 'nobr',
			loop: false,
			stepunit: 1,
			steptime: 20,
			waittime: 1000
		}, options||{});
		var timer, timer2, ml = 0, w = 0, element = elm.find(settings.items);
		if (settings.items == 'nobr') {
			w = element.width();
		} else if (settings.items == 'ul') {
			var w = 0;
			elm.find('li').each(function() {
				w += $(this).outerWidth();
			});
			elm.css('width', w+100+'px');		
		}
		if (w <= elm.width()) return;
		var start = function() {
			timer = setInterval(function() {
				if (ml > w) {
					if (settings.loop) {
						ml = 0 - elm.width();
						element.css('margin-left', 0-ml);
					} else {
						stop();
						element.css({
							'margin-left': 0,
							'margin-top': 0-elm.height()
						}).stop().animate({'margin-top':0}, 1000, function() {
							ml = 0;
							timer2 = setTimeout(start, settings.waittime);
						});
					}
				} else {
					ml += settings.stepunit;
					element.css('margin-left', 0-ml);
				}
			}, settings.steptime);
		};
		var stop = function() {
			clearInterval(timer);
			clearInterval(timer2);
		};
		elm.hover(function() {
			stop();
		}, function() {
			start();
		});
		setTimeout(start, settings.waittime);
	};
	// ----------------------------
	// 空白区点击事件绑定
	YM.ui.BindOuterClickEvent = function(elm, callback) {
		var cancelBubble = function(e) {
			if (e.stopPropagation) {
				e.stopPropagation();
			} else {
				e.cancelBubble = true;
			}			
		};
		var elmEvent = function(e) {
			callback();
			elm.unbind('click', cancelBubble);
			$(document).unbind('click', elmEvent);
		};
		elm.bind('click', cancelBubble);
		$(document).bind('click', elmEvent);
	};
	// ----------------------------
	YM.ui.LoadMVC = function(elm) {
		if (elm.data('LoadMVC-binded')) return;
		elm.each(function() {
			if (!$(this).attr('data-mvc')) return;
			var mvc = $(this).attrJSON('data-mvc');
			var id = mvc.name || this.id || 'mvc'+new Date().getTime();
			YM.load.add(id, mvc);
			YM.load(id);
		});
	};
	// ----------------------------
	YM.ui.LoadElementEvent = function(elm, attr) {
		if (elm.data('LoadElementEvent-binded')) return;
		elm.each(function() {
			var attrValue = $(this).attr(attr||'data-onload') || '';
			if (attrValue) eval(attrValue);
		});
	};
	// ----------------------------
	YM.timestat.add('load-ym-ui');
	YM.debug('YM.ui.js', '初始化成功');
})(jQuery);